import { defineStore } from 'pinia'

export const useAppStore = defineStore('app', {
  state: () => ({
    isLoading: false,
    theme: 'light',
    language: 'zh-cn',
    sidebarCollapsed: false,
    notifications: []
  }),

  getters: {
    isDarkMode: (state) => state.theme === 'dark'
  },

  actions: {
    setLoading(loading) {
      this.isLoading = loading
    },

    toggleTheme() {
      this.theme = this.theme === 'light' ? 'dark' : 'light'
      localStorage.setItem('theme', this.theme)
    },

    toggleSidebar() {
      this.sidebarCollapsed = !this.sidebarCollapsed
      localStorage.setItem('sidebarCollapsed', this.sidebarCollapsed)
    },

    addNotification(notification) {
      const id = Date.now()
      this.notifications.push({
        id,
        ...notification,
        timestamp: new Date()
      })
      
      // 自动移除通知
      if (notification.duration !== 0) {
        setTimeout(() => {
          this.removeNotification(id)
        }, notification.duration || 4000)
      }
    },

    removeNotification(id) {
      const index = this.notifications.findIndex(n => n.id === id)
      if (index > -1) {
        this.notifications.splice(index, 1)
      }
    },

    showSuccess(message) {
      this.addNotification({
        type: 'success',
        message,
        title: '成功'
      })
    },

    showError(message) {
      this.addNotification({
        type: 'error',
        message,
        title: '错误',
        duration: 6000
      })
    },

    showWarning(message) {
      this.addNotification({
        type: 'warning',
        message,
        title: '警告'
      })
    },

    showInfo(message) {
      this.addNotification({
        type: 'info',
        message,
        title: '信息'
      })
    },

    initialize() {
      // 从本地存储恢复设置
      const theme = localStorage.getItem('theme')
      if (theme) {
        this.theme = theme
      }
      
      const sidebarCollapsed = localStorage.getItem('sidebarCollapsed')
      if (sidebarCollapsed !== null) {
        this.sidebarCollapsed = JSON.parse(sidebarCollapsed)
      }
      
      const language = localStorage.getItem('language')
      if (language) {
        this.language = language
      }
    }
  }
})